<?php

/*
 * 心愿相关
 * @auth bzyy
 * 2015-6-16 14:33:16
 */

class WishModel extends BaseModel
{
	var $table  = 'wish';
	var $prikey = 'wish_id';
	const MAX_DAY = 20;

    /**
     * 已经结束，不需要退款
     * @author jyx
     * @date 2015/08/07
     */
    const OVER_NO_BACK_MONEY = 1;
    /**
     * 已结束待退款
     * @author jyx
     * @date 2015/08/07
     */
    const WAIT_BACK_MONEY = 2;
	/**
	 * 添加心愿的处理
	 * @auth bzyy
	 * 2015-6-16 14:34:28
	 */   
	public function add($data,$user_id)
	{
		$goods_id = intval($data['goods_id']);
		$spec_id = intval($data['spec_id']);
		
		$now = time();
		$f = $this->effect($goods_id, $spec_id,$user_id);
		if(!$f)
		{
			return false;
		}
		
		$wish_total_day = intval($data['wish_total_time']);
		unset($data['wish_total_time']);
		if($wish_total_day<1){
			$this->_errors['error'] = '请选择正确的天数';
			return false;
		}
		
		$data['start_time'] = $now;
		$data['end_time'] = $now + 86400 * $wish_total_day;
		
		$data['title'] = trim($data['title']);
		if(empty($data['title']))
		{
			$this->_errors['title'] = '标题不可为空';
			return false;
		}
		if(strlen($data['title'])>500)
		{
			$this->_errors['title'] = '标题内容过长';
			return false;
		}

		$data['flag'] = 0;
		$data['user_id'] = $user_id;
		
		$f = parent::add($data);
		if(!$f)
		{
			$this->_errors['error'] = '添加数据时发生错误';
			return false;
		}

		
		return $f;
	}
	
	/*
	 * 取得一个有效心愿的信息
	 * @auth bzyy
	 * 2015-6-16 15:52:49
	 */
	public function infoOk($id,$checktime=true)
	{
		$info = $this->get("wish_id='{$id}'");
		if(empty($info))
		{
			$this->_errors['error'] = '信息不存在';
			return false;
		}
		
		if($info['flag'])
		{
			$this->_errors['error'] = '该心愿已经结束了';
			return false;
		}
		
		if($checktime)
		{
			$time = time();
			
			if($info['start_time']>$time)
			{
				$this->_errors['error'] = '心愿时间还未到开始时间';
				return false;
			}
			
			if($info['end_time']>0 && $info['end_time']<$time)
			{
				$this->_errors['error'] = '心愿时间已经结束';
				return false;
			}
		}
		
		//检测商品等的正确性
		$f = $this->effect($info['goods_id'], $info['spec_id']);
		if(!$f)
		{
			return false;
		}
		
		return $info;
		
	}
	
	/*
	 * 检测商品的有效性
	 * @auth bzyy
	 * 2015-6-17 10:28:41
	 */
	public function effect($goods_id,$spec_id,$user_id=0)
	{
		$now = time();
		//检测是否有一个正在分享状态的一个心愿记录
		if($user_id)//添加时候的验证
		{
			$sql = "select count(*) from ".$this->table." where goods_id='{$goods_id}' and user_id='{$user_id}' and spec_id='{$spec_id}' and end_time>'{$now}' and flag='0' ";
			
			$c = $this->getOne($sql);
			if($c>0)
			{
				$this->_errors['hasone'] = '您已经添存在一个未结束同样的心愿了。';
				return false;
			}
		}
		//规格的检测
		$sql = "select spec_id,goods_id,spec_1,spec_2,price,stock,spec_supply_price from ".DB_PREFIX."goods_spec where goods_id='{$goods_id}' and spec_id='{$spec_id}' ";
		$sepc_info = $this->getRow($sql);
		if(empty($sepc_info))
		{
			$this->_errors['error'] = '未找到商品规格';
			return false;
		}
		
		if($sepc_info['stock']<1)
		{
			$this->_errors['error'] = '此商品库存不足';
			return false;
		}
		
		//商品信息的检测
		$sql = "select g.goods_id,g.goods_name,g.store_id,introduction,spec_name_1,spec_name_2,default_image,cate_id_1,cate_id_2,cate_id_3,cate_id_4,price,tags,market_price,store_name from ".DB_PREFIX."goods as g LEFT JOIN ".DB_PREFIX."store as s ON g.store_id=s.store_id
		where goods_id='{$goods_id}' and  g.if_examine = 1 AND g.if_finance = 1 AND g.if_show = 1 AND g.closed = 0
		and s.state=1 ";
		$goods_info = $this->getRow($sql);
		if(empty($goods_info))
		{
			$this->_errors['error'] = '商品不存在或处于待审核状态';
			return false;
		}
		
		return array('spec'=>$sepc_info,'goods'=>$goods_info);
	}
	
	
	/*
	 * 手机端心愿列表
	 * @auth bzyy
	 * 2015-6-17 11:13:10
	 * 
	 * 默认为所有人看到的列表
	 */
	public function applist($condition='1',$limit)
	{
        //查询未结束的心愿单列表
		$sql = "select w.wish_id,w.goods_id,w.spec_id,w.title,g.price,g.default_image from ".$this->table
		." as w LEFT JOIN ".DB_PREFIX."goods as g on w.goods_id=g.goods_id
		where {$condition} and flag = 0 order by w.wish_id desc {$limit}";

		$data = $this->getAll($sql);

		if(empty($data))
		{
			return array();
		}
		
		$domain = get_domain().'/';
		$goods_ids = array();
		$spec_ids = array();
		foreach ($data as $key => $val)
		{
			//默认图片
            if (strpos($val['default_image'], FARFETCH_URL) === false) {
                if (strpos($val['default_image'], ZHAYAN_URL) === false) {
                    $data[$key]['default_image'] = $val['default_image'] ? QINIU_URL . $val['default_image'] : $domain . Conf::get('default_goods_image');
                }
            }
			//心愿完成人数
			//规格的统计
			$goods_ids[$val['wish_id']] = $val['goods_id'];
			$spec_ids[] = $val['spec_id'];
		}
		
		//找到对应的规格
		$sql = "select spec_id,goods_id,spec_1,spec_2,stock,price,sku from ".DB_PREFIX."goods_spec where spec_id ".db_create_in($spec_ids);
		$specs = $this->getAll($sql);
		$spec_datas = array();
		foreach ($specs as $val)
		{
			$spec_datas[$val['spec_id']] = $val;
		}
		
		//有关于心愿的人数统计
		$sql = "select wish_id,count(wish_log_id) as c,sum(donate_price) as paymoney from ".DB_PREFIX."wish_log where wish_id ".db_create_in(array_keys($goods_ids))." and status=1 group by wish_id ";
		$wish_count = $this->getAll($sql);
		$wishc_data = array();
		foreach ($wish_count as $val)
		{
			$wishc_data[$val['wish_id']] = $val;
		}
		
		foreach ($data as $key=>$val)
		{
			$val['price'] = isset($spec_datas[$val['spec_id']])?$spec_datas[$val['spec_id']]['price']:$val['price'];
			$val['remain_price'] = $val['price'];
			$val['total'] = 0;
			if(isset($wishc_data[$val['wish_id']]))
			{
				$val['remain_price'] = $val['remain_price']-$wishc_data[$val['wish_id']]['paymoney'];
				$val['remain_price'] = floatval($val['remain_price']);
				
				$val['total'] = $wishc_data[$val['wish_id']]['c'];
			}
			$data[$key]['remain_price'] = floatval($val['remain_price']);
			$data[$key]['price'] = $val['price'];
			$data[$key]['total'] = floatval($val['total']);

		}
		
		
		return $data;
	}
	
	/*
	 * app详情数据
	 * @auth bzyy
	 * 2015-6-17 13:48:02
	 */
	public function detail($user_id, $wish_id, $limit)
	{
		$config = require ROOT_PATH.'/data/config.qiniu.php';
		$sql = "select w.*,g.goods_name,g.price,g.introduction,s.store_logo,s.store_name from ".DB_PREFIX."wish as w
                LEFT JOIN ".DB_PREFIX."goods as g ON w.goods_id=g.goods_id LEFT JOIN ".DB_PREFIX."store s
                ON g.store_id=s.store_id WHERE w.wish_id='{$wish_id}' AND w.user_id={$user_id}";
		$info = $this->getRow($sql);
		if(empty($info))
		{
			$this->_errors['error'] = '心愿不存在';
			return false;	
		}
		
		$goods_id = $info['goods_id'];
		$spec_id = $info['spec_id'];

		$more_info = $this->effect($goods_id, $spec_id);
		if(empty($more_info))
		{
			return false;
		}

		$spec = $more_info['spec'];
		$goods_info = $more_info['goods'];
		
		$now = time();
		$domain = get_domain().'/';
		$data = array();
		$sql = "SELECT user_id FROM ".DB_PREFIX."collect WHERE user_id={$user_id} AND item_id={$goods_id} AND type='goods'";
		$tmp = $this->getRow($sql);
		$data['flollow'] = $tmp ? 1 : 0;
        $data['store_logo'] = $info['store_logo'] ? QINIU_URL.$info['store_logo'] : $domain.Conf::get('default_store_logo');
        $data['store_name'] = $info['store_name'];
		$data['goods_id'] = $info['goods_id'];
		$data['introduction'] = $info['introduction'];
		$data['wish_id'] = $info['wish_id'];
		$data['spec_id'] = $info['spec_id'];
		$data['collects'] = 0;
		$data['price'] = $more_info['spec']['price'];
		$data['remain_price'] = $data['price'];
		$data['total'] = 0;
		$data['over_time'] = 0;
		$data['goods_name'] = $info['goods_name'];
		
		$data['spec_name_1'] = $goods_info['spec_name_1'];
		$data['spec_name_2'] = $goods_info['spec_name_2'];
		$data['spec_1'] = $spec['spec_1'];
		$data['spec_2'] = $spec['spec_2'];
		
		if($info['end_time']>$now)
		{
			$data['over_time'] = round(($info['end_time']-$now)/86400);
		}
		
		//统计信息
		$sql = "select count(*) as c,sum(donate_price) as price from ".DB_PREFIX."wish_log where wish_id='{$wish_id}' and status=1 ";
		$c_info = $this->getRow($sql);
		$data['total'] = $c_info['c'];
		
		$data['remain_price'] -= $c_info['price'];
		$data['remain_price'] = max(0,$data['remain_price']);
		
		$sql = "select collects,base_collects from ". DB_PREFIX ."goods_statistics  where goods_id='{$goods_id}' ";
		$cc = $this->getRow($sql);
        $collects = $cc['collects'] + $cc['base_collects'];
		$data['collects'] = $collects ? intval($collects) : 0;
		
		//商品图片
		$sql = "select image_id,thumbnail from ".DB_PREFIX."goods_image where goods_id='{$goods_id}' order by sort_order ";
		$imgs = $this->getAll($sql);
		$images = array();
		foreach ($imgs as $val)
		{
            if (strpos($val['thumbnail'], FARFETCH_URL) === false) {
                if (strpos($val['thumbnail'], ZHAYAN_URL) === false) {
                    $val['thumbnail'] = QINIU_URL.$val['thumbnail'];
                }
            }
			$images[] = $val;
		}
		$data['image'] = $images;
		
		//支付心愿日志
		$domain = get_domain().'/';
		
		$sql = "select wl.donate_time,wl.donate_price,wl.wish_log_id,m.nickname,m.portrait,m.gender from ".DB_PREFIX."wish_log as wl LEFT JOIN ".DB_PREFIX."member as m ON wl.user_id=m.user_id
				where wl.wish_id='{$wish_id}' and status=1 order by wl.wish_log_id asc {$limit} ";
		$logs = $this->getAll($sql);
		$wish = array();
		foreach ($logs as $val) {
			$temp = array();
			$temp['portrait'] = $val['portrait'] ? $val['portrait'] : $domain.'data/system/default_user_portrait.gif';
			$temp['user_name'] = $val['nickname'] ? $val['nickname'] : '热心网友';
			$temp['sex'] = $val['gender'] == 2 ? 0 : 1;
			$temp['donate_time'] = date('Y-m-d',$val['donate_time']);
			$temp['donate_price'] = $val['donate_price'];
			$wish[] = $temp;
		}
		
		$data['wish'] = $wish;
		
		$data['remain_price'] = floatval($data['remain_price']);
		
		return $data;
		
	}

    /**
     * 关闭一个心愿
     * @param $wish_id
     * @param $user_id
     * @param bool|false $state
     * @return bool
     * @author jyx
     * @date 2015/08/07
     */
	public function close($wish_id, $user_id, $state = false)
	{
		$info = $this->get("wish_id='{$wish_id}' ");
		
		if(empty($info))
		{
			$this->_errors['error'] = '心愿不存在';
			return false;
		}
		
		
		if($info['flag'] == 1)
		{
			return true;
		}
		
		if($info['user_id'] != $user_id)
		{
			$this->_errors['error'] = '您无权操作此项';
			return false;
		}
		
		$flag = $state === true ? self::WAIT_BACK_MONEY : self::OVER_NO_BACK_MONEY;
		
		$f = $this->edit($wish_id, array('flag'=>$flag));
		if(!$f)
		{
			$this->_errors['error'] = '修改时失败';
			return false;
		}
		return true;
	}
	
	/**
	 * 检测用户还需要付款多少
	 * @auth bzyy
	 * 2015-6-23 18:59:58
	 * 
	 * $logistics 支付方式
	 */
	public function moremoney($info){
		//统计总的费用,找到规格
		$sql = "select spec_id,goods_id,spec_1,spec_2,price,stock,sku,spec_supply_price,color_rgb from ".DB_PREFIX."goods_spec where spec_id='{$info['spec_id']}' ";
		$spec = $this->getRow($sql);
		if(empty($spec))
		{
			$this->_errors['error'] = '未找到规格';
			return false;
		}
		
		$data_info = array();
		$data_info['price'] = $spec['price'];
		//统计支付总费用
		
		$sql = "select sum(donate_price) as money from ".DB_PREFIX."wish_log where status=1 and wish_id={$info['wish_id']} and refund_status=0 ";
		$data = $this->getOne($sql);
		
		
		$data_info['paymoney'] = round($data,2);

		
		$data_info['repay_money'] = $data_info['price'] - $data_info['paymoney'];
		$data_info['repay_money'] = round($data_info['repay_money'],2);
		$data_info['repay_money'] = max($data_info['repay_money'],0);
		$data_info['spec'] = $spec;
		return $data_info;
		
	}

	/*
	 * 生成一个心愿订单数据
	 * @auth bzyy
	 * 2015-6-23 20:38:19
	 *
	 * 此方法被弃用，不需再次优化处理
	 */
	public function corder($info,$consignee_info,$addon_info){
		$order_model =& m('order');
		$sql = "select user_name,email from ".DB_PREFIX."member where user_id='{$info['user_id']}'";
		$user = $order_model->getRow($sql);
		if(empty($user))
		{
			$this->_errors['error'] = '用户信息不存在';
			return false;
		}
		
		$domain = get_domain().'/';
		$store_info = array();
		$goods_info = array();
		$sql = "select s.store_name,s.store_logo,s.store_id,g.goods_name,g.default_image,g.spec_name_1,g.spec_name_2,g.supply_price from ".DB_PREFIX."store as s LEFT JOIN ".DB_PREFIX."goods as g ON s.store_id = g.store_id where goods_id='{$info['goods_id']}' ";
		$store = $order_model->getRow($sql);
		if(empty($store) || empty($store['store_name']))
		{
			$this->_errors['error'] = '店铺信息不存在';
			return false;
		}
		
		$spec = array();
		$spec['spec_id'] = $addon_info['spec']['spec_id'];
		$spec['spec_1'] = $addon_info['spec']['spec_1'];
		$spec['spec_2'] = $addon_info['spec']['spec_2'];
		$store_info['store_name'] = $store['store_name'];
		$store_info['store_logo'] = empty($store['store_logo'])?$domain.Conf::get('default_store_logo'):QINIU_URL.$store['store_logo'];
		$goods_info['goods_name'] = $store['goods_name'];
		$goods_info['spec_name_1'] = $store['spec_name_1'];
		$goods_info['spec_name_2'] = $store['spec_name_2'];
		$goods_info['default_image'] = empty($store['default_image'])?$domain.Conf::get('default_goods_image'):QINIU_URL.$store['default_image'];
		$postscript = $consignee_info['postscript'];
		unset($consignee_info['postscript']);
		
		$info['specification'] = '';
		if(!empty($store['spec_name_1']))
		{
			$info['specification'] .= $store['spec_name_1'].":".$addon_info['spec']['spec_1'];
		}
		if(!empty($store['spec_name_2']))
		{
			$info['specification']  = empty($info['specification'])?'':$info['specification'].' ';
			$info['specification'] .= $store['spec_name_2'].":".$addon_info['spec']['spec_2'];
		}
		$sql = "select * from ".DB_PREFIX."member where user_id='{$store['store_id']}'";
		$seller = $order_model->getRow($sql);
		
		$info['supply_amount'] = $addon_info['spec']['supply_price']>0?$addon_info['spec']['supply_price']:$store['supply_price'];
		$base_info = array(
				'order_sn'      =>  $this->_gen_order_sn(),
				'type'          =>  '',
				'extension'     =>  'normal',
				'seller_id'     =>  $store['store_id'],
				'seller_name'   =>  addslashes($store['store_name']),
				'buyer_id'      =>  $info['user_id'],
				'buyer_name'    =>  addslashes($user['user_name']),
				'buyer_email'   =>  $user['email'],
				'status'        =>  0,
				'add_time'      =>  gmtime(),
				'goods_amount'  =>  $addon_info['price'],
				'supply_amount' =>  $info['supply_amount'],
				'discount'      =>  $addon_info['paymoney'],
				'anonymous'     =>  0,
				'postscript'    =>  addslashes($postscript),
		);
		
		//当前不考虑运费
		$base_info['order_amount'] = $base_info['goods_amount'] + $consignee_info['shipping_fee'] - $base_info['discount'];
		$base_info['order_amount'] = max(0,$base_info['order_amount']);
		$base_info['order_amount'] = round($base_info['order_amount'],2);
		
		if($base_info['order_amount'] == 0)
		{//不需要支付的处理
			$base_info['status'] = 20;
		}

		$base_info['order_amount'] = $base_info['goods_amount'] + $consignee_info['shipping_fee'];
		
		$order_id    = $order_model->add($base_info);
		if(!$order_id)
		{
			$this->_errors['error'] = '添加订单时出错';
			return false;
		}
		/* 插入收货人信息 */
		$consignee_info['order_id'] = $order_id;
		$order_extm_model = m('orderextm');
		$order_extm_model->add($consignee_info);
		
		
		/* 插入商品信息 */
		$goods_items = array();
		
		$goods_items[] = array(
				'order_id'      =>  $order_id,
				'goods_id'      =>  $info['goods_id'],
				'goods_name'    =>  $store['goods_name'],
				'spec_id'       =>  $info['spec_id'],
				'specification' =>  $info['specification'],//属性
				'price'         =>  $addon_info['price'],
				'supply_price'  =>  $info['supply_amount'],
				'quantity'      =>  1,
				'goods_image'   =>  $info['goods_image'],
		);
		
		$order_goods_model = m('ordergoods');
		$order_goods_model->add(addslashes_deep($goods_items)); //防止二次注入
		$base_info['shipping_fee'] = $consignee_info['shipping_fee'];
		$base_info['order_id'] = $order_id;
		$goods_info['spec'] = $spec;
		$goods_info['store'] = $store_info;
		$base_info['goods'] = array($goods_info);

		//减少库存
		$sql = "update ". DB_PREFIX ."goods_spec set stock=stock-1 where spec_id='{$spec['spec_id']}' limit 1 ";
		$this->query($sql);
		
		return $base_info;
	}
	
	public function _gen_order_sn()
	{
		/* 选择一个随机的方案 */
		mt_srand((double) microtime() * 1000000);
		$timestamp = gmtime();
		$y = date('y', $timestamp);
		$z = date('z', $timestamp);
		$order_sn = $y . str_pad($z, 3, '0', STR_PAD_LEFT) . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
	
		$model_order = m('order');
		$orders = $model_order->find('order_sn=' . $order_sn);
		if (empty($orders))
		{
			/* 否则就使用这个订单号 */
			return $order_sn;
		}
	
		/* 如果有重复的，则重新生成 */
		return $this->_gen_order_sn();
	}
	
	
}



?>